package com.cyh.core.framework.common.utils;

import com.cyh.core.framework.common.constant.RedisConstant;
import com.cyh.core.login.entity.User;
import com.cyh.core.login.repository.RoleRepository;
import com.cyh.core.login.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserTokenUtil {

    @Value("${cyh.constant.time.TokenTime}")
    private int TokenTime;

    @Value("${cyh.constant.time.RedisUserTime}")
    private int redisUserTime;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    UsersRepository usersRepository;

    @Autowired
    RoleRepository roleRepository;

    private UserTokenUtil(){

    }

    public User getCurrentUser() {
        String token=null;
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        token=request.getHeader("Cookie");
        if (token == null){
            return null;
        }
        token = token.replace("token=","");
        return getUserFromToken(token);
    }

    public User getUserFromToken(String token){
        String userId=JWTUtil.GetIdFromToken(token);
        User user =null;
        String str="  Update ";
        try {
            user=(User) redisUtil.get(RedisConstant.LOGIN_USER_HASH+":"+token);
            if(user.getTempObject()==null){
                user.setTempObject(roleRepository.findByRoleid(user.getRoleid()));
            }
        }catch (Exception e){
            user=null;
        }
        if(user==null) {
            user = usersRepository.findById(Integer.parseInt(userId)).get();
            if(user == null){
                return null;
            }
            user.setTempObject(roleRepository.findByRoleid(user.getRoleid()));
            str="  Re Add ";
            System.out.println(TimeUtil.getNow()+"  User From Repository "+user);
        }else {
            System.out.println(TimeUtil.getNow()+"  User From Redis "+user);
        }
        try {
            redisUtil.set(RedisConstant.LOGIN_USER_HASH+":"+token,user,redisUserTime*60);
            //redisUtil.hset(RedisConstant.LOGIN_USER_HASH, token, user, redisUserTime * 60);
            System.out.println(TimeUtil.getNow()+str+user+" To Redis...");
        }catch (Exception e){
            return null;
        }
        return user;
    }

}
